<template>
  <div class="code-block-container glass-effect" :class="{ 'dark-theme': isDark }">
    <div class="code-header">
      <div class="code-language">{{ language }}</div>
      <div class="code-actions">
        <button 
          class="theme-toggle" 
          @click="toggleTheme" 
          title="切换主题"
          :class="{ active: isDark }"
        >
          {{ isDark ? '☀️' : '🌙' }}
        </button>
        <button 
          class="copy-button" 
          @click="copyCode" 
          :class="{ copied: isCopied }"
          :title="isCopied ? '已复制!' : '复制代码'"
        >
          {{ isCopied ? '✅' : '📋' }}
        </button>
      </div>
    </div>
    <div class="code-wrapper">
      <div v-if="showLineNumbers" class="code-grid">
        <div class="line-numbers-cell">
          <div 
            v-for="index in lineCount" 
            :key="index" 
            class="line-number"
          >
            {{ index }}
          </div>
        </div>
        <div class="code-cell">
          <pre><code :class="`language-${language}`" v-html="highlightedCode"></code></pre>
        </div>
      </div>
      <div v-else>
        <pre><code :class="`language-${language}`" v-html="highlightedCode"></code></pre>
      </div>
      </div>
    </div>
  </template>

<script setup>
import { ref, computed, onMounted, watch, inject } from 'vue'
// 导入highlight.js的完整版本，它自带对多种语言的支持
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css'
import 'highlight.js/styles/github-dark.css'
// 导入theme store
import { useThemeStore } from '../store/theme.js'

const themeStore = useThemeStore()

// Props定义
const props = defineProps({
  code: {
    type: String,
    required: true
  },
  language: {
    type: String,
    default: 'javascript'
  },
  showLineNumbers: {
    type: Boolean,
    default: true
  },
  defaultDarkMode: {
    type: Boolean,
    default: false
  }
})

// 响应式状态
const isDark = ref(props.defaultDarkMode)
// 保存代码块独立主题设置的key
const blockThemeKey = `codeBlockTheme_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
const isCopied = ref(false)

// 计算代码行数
const lineCount = computed(() => {
  const decodedCode = decodeHtmlEntities(props.code)
  return decodedCode.split('\n').length
})

// 解码HTML转义字符
const decodeHtmlEntities = (html) => {
  const entities = {
    '&lt;': '<',
    '&gt;': '>',
    '&amp;': '&',
    '&quot;': '"',
    '&#39;': "'",
    '&#123;': '{',
    '&#125;': '}'
  }
  
  return html ? html.replace(/&lt;|&gt;|&amp;|&quot;|&#39;|&#123;|&#125;/g, (match) => entities[match]) : ''
}

// 计算高亮后的代码
const highlightedCode = computed(() => {
  try {
    const decodedCode = decodeHtmlEntities(props.code)
    
    // 针对Vue代码的特殊处理
    if (props.language === 'vue') {
      // 尝试直接使用highlight.js的Vue语言支持
      try {
        return hljs.highlight(decodedCode, { language: 'vue' }).value
      } catch (e) {
        // 如果Vue语言支持不可用，使用自动检测模式
        return hljs.highlightAuto(decodedCode, ['javascript', 'html']).value
      }
    }
    
    // 其他语言正常处理
    return hljs.highlight(decodedCode, { language: props.language }).value
  } catch (error) {
    // 发生任何错误时，使用自动检测模式作为最后的后备方案
    const decodedCode = decodeHtmlEntities(props.code)
    return hljs.highlightAuto(decodedCode).value
  }
})

// 切换主题（独立控制，不影响全局）
const toggleTheme = () => {
  isDark.value = !isDark.value
  // 保存当前代码块的独立主题设置
  localStorage.setItem(blockThemeKey, isDark.value ? 'dark' : 'light')
}

// 复制代码
const copyCode = async () => {
  try {
    const decodedCode = decodeHtmlEntities(props.code)
    await navigator.clipboard.writeText(decodedCode)
    isCopied.value = true
    setTimeout(() => {
      isCopied.value = false
    }, 2000)
  } catch (err) {
    console.error('复制失败:', err)
  }
}

// 组件挂载
onMounted(() => {
  // 首先尝试恢复当前代码块的独立主题设置
  const savedBlockTheme = localStorage.getItem(blockThemeKey)
  if (savedBlockTheme) {
    isDark.value = savedBlockTheme === 'dark'
  } else {
    // 如果没有独立设置，则跟随全局主题
    isDark.value = themeStore.appTheme === 'dark'
  }
  
  // 监听全局主题变化
  window.addEventListener('code-theme-changed', handleGlobalThemeChange)
})

// 处理全局主题变化
const handleGlobalThemeChange = (event) => {
  // 检查当前代码块是否有独立的主题设置
  const hasIndependentSetting = localStorage.getItem(blockThemeKey) !== null
  
  // 如果没有独立设置，则跟随全局主题变化
  if (!hasIndependentSetting) {
    // 根据全局应用主题决定代码块主题
    isDark.value = themeStore.appTheme === 'dark'
  }
}

// 组件卸载时移除事件监听
import { onUnmounted } from 'vue'
onUnmounted(() => {
  window.removeEventListener('code-theme-changed', handleGlobalThemeChange)
})
</script>

<style scoped>
.code-block-container {
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  margin: 1rem 0;
  transition: all 0.3s ease;
  border: 1px solid #e1e4e8;
}

/* 玻璃拟态效果 */
.glass-effect {
  background: rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);
}

/* 深色模式下的玻璃效果 */
[data-theme="dark"] .glass-effect {
  background: rgba(31, 41, 55, 0.7);
  border: 1px solid rgba(255, 255, 255, 0.1);
  box-shadow: 0 4px 30px rgba(0, 0, 0, 0.3);
}

.code-block-container.dark-theme {
  border-color: #30363d;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

.code-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.75rem 1rem;
  background: #f6f8fa;
  border-bottom: 1px solid #e1e4e8;
}

.dark-theme .code-header {
  background: #1f2937;
  border-bottom-color: #30363d;
}

.code-language {
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 0.875rem;
  color: #6a737d;
  font-weight: 500;
}

.dark-theme .code-language {
  color: #9ca3af;
}

.code-actions {
  display: flex;
  gap: 0.5rem;
}

.theme-toggle,
.copy-button {
  background: none;
  border: 1px solid transparent;
  padding: 0.375rem 0.75rem;
  border-radius: 6px;
  cursor: pointer;
  font-size: 1rem;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.theme-toggle:hover,
.copy-button:hover {
  background: #e1e4e8;
}

.dark-theme .theme-toggle:hover,
.dark-theme .copy-button:hover {
  background: #374151;
}

.theme-toggle.active {
  background: #e1e4e8;
}

.dark-theme .theme-toggle.active {
  background: #374151;
}

.copy-button.copied {
  background: #10b981;
  color: white;
}

/* 代码包装器 - 处理滚动 */
.code-wrapper {
  overflow: auto;
  max-height: 500px;
  background: white;
}

.dark-theme .code-wrapper {
  background: #111827;
}

/* CSS Grid 布局容器 */
.code-grid {
  display: grid;
  grid-template-columns: auto 1fr;
  gap: 0;
  width: fit-content;
  min-width: 100%;
}

/* 行号单元格 */
.line-numbers-cell {
  background-color: rgba(255, 255, 255, 0.5);
  color: #6a737d;
  text-align: right;
  padding: 1rem 0.75rem 1rem 0.5rem;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 0.875rem;
  line-height: 1.5;
  user-select: none;
  min-width: 3.5rem;
  border-right: 1px solid #e1e4e8;
  overflow: hidden;
  box-sizing: border-box;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.dark-theme .line-numbers-cell {
  background-color: rgba(0, 0, 0, 0.2);
  color: #858585;
  border-right: 1px solid #30363d;
}

/* 行号元素 */
.line-number {
  height: 1.5em;
  line-height: 1.5;
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-indent: 0;
  letter-spacing: 0;
  word-spacing: 0;
  vertical-align: baseline;
  display: block;
}

/* 代码单元格 */
.code-cell {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

/* 代码块样式 */
pre {
  margin: 0;
  padding: 1rem;
  background: transparent;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 0.875rem;
  line-height: 1.5;
  white-space: pre;
  word-wrap: normal;
  box-sizing: border-box;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  min-height: 100%;
  text-indent: 0;
  letter-spacing: 0;
  word-spacing: 0;
  vertical-align: baseline;
  tab-size: 2;
}

/* 确保代码块和行号容器在滚动时保持同步 */
pre::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

pre::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.dark-theme pre::-webkit-scrollbar-track {
  background: #1f2937;
}

pre::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.dark-theme pre::-webkit-scrollbar-thumb {
  background: #4b5563;
}

pre::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.dark-theme pre::-webkit-scrollbar-thumb:hover {
  background: #6b7280;
}

/* 代码元素样式 */
code {
  font-family: inherit;
  font-size: inherit;
  line-height: inherit;
  white-space: inherit;
  background: transparent !important;
  padding: 0 !important;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.dark-theme pre {
  color: #d1d5db;
}



/* 当不显示行号时调整内边距 */
:deep(.code-wrapper > div:not(.code-grid)) pre {
  padding-left: 1rem;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .code-block-container {
    font-size: 0.8rem;
  }
  
  .code-header {
    padding: 0.5rem 0.75rem;
  }
  
  pre {
    padding: 0.75rem;
  }
  
  .line-numbers-cell {
    min-width: 30px;
    font-size: 0.8rem;
    padding-right: 0.5rem;
    padding-left: 0.25rem;
  }
}
</style>

<style>
/* 覆盖highlight.js的默认样式以适配深色主题 */
.dark-theme .hljs {
  background: #111827 !important;
  color: #d1d5db !important;
}

/* 确保深色主题下代码高亮正确显示 */
.dark-theme .hljs-keyword,
.dark-theme .hljs-selector-tag,
.dark-theme .hljs-subst {
  color: #f472b6 !important;
}

.dark-theme .hljs-string,
.dark-theme .hljs-attr,
.dark-theme .hljs-symbol,
.dark-theme .hljs-bullet,
.dark-theme .hljs-addition {
  color: #4ade80 !important;
}

.dark-theme .hljs-title,
.dark-theme .hljs-section,
.dark-theme .hljs-attribute {
  color: #60a5fa !important;
}

.dark-theme .hljs-variable,
.dark-theme .hljs-template-variable {
  color: #facc15 !important;
}

.dark-theme .hljs-comment,
.dark-theme .hljs-quote,
.dark-theme .hljs-deletion {
  color: #9ca3af !important;
}

.dark-theme .hljs-number,
.dark-theme .hljs-regexp,
.dark-theme .hljs-literal,
.dark-theme .hljs-type {
  color: #fbbf24 !important;
}

.dark-theme .hljs-built_in,
.dark-theme .hljs-builtin-name {
  color: #60a5fa !important;
}

.dark-theme .hljs-meta {
  color: #a78bfa !important;
}

.dark-theme .hljs-emphasis {
  font-style: italic !important;
}

.dark-theme .hljs-strong {
  font-weight: bold !important;
}
</style>